<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>tab切换</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        .box {
            width: 600px;
            height: 300px;
            border: 1px solid skyblue;
            margin: 50px auto;
        }

        .menu .list {
            list-style-type: none;
            float: left;
            cursor: pointer;
            width: 200px;
            line-height: 40px;
            text-align: center;
            border: 1px solid #87ceeb;
            box-sizing: border-box;
        }

        .content .main {
            padding: 20px;
            display: none;
            text-indent: 20px;
            word-wrap: break-word;
        }

        .content .selected {
            display: block;
        }

        .active {
            background-color: pink;
        }
    </style>
</head>

<body>

    <div class="box">
        <div class="menu">
            <ul>
                <li class="list active">Html</li>
                <li class="list">JavaScript</li>
                <li class="list">Vue</li>
            </ul>
        </div>
        <div class="content">
            <div class="main selected"></div>
            <div class="main"></div>
            <div class="main"></div>
        </div>
    </div>

    <script src="./js/axios.js"></script>
    <script>
        //1、获取tab类名
        let lisELe = document.querySelectorAll('.box .menu .list');
        let mainEle = document.querySelectorAll('.box .content .main');
        // console.log(lisELe);
        //2、循环绑定单机事件
        [...lisELe].forEach(function (liEle, index) {
            liEle.addEventListener('click', async function () {
                // 排他思想：
                // 先移除其他元素的active类名，后给当前单击(this)的元素添加类名active
                [...lisELe].forEach(function (item) {
                    item.classList.remove("active");
                });
                this.classList.add("active");

                // 先把所有类名为main元素都移除selected类名，
                [...mainEle].forEach(function (item) {
                    item.classList.remove("selected");
                });
                // 后把单击相同的下标元素添加类名selected
                [...mainEle][index].classList.add("selected");


                // 需求：减少服务器的请求压力，请求只执行一次
                if ([...mainEle][index].innerText) {
                    // 如果有内容则不发请求
                    return;
                }

                // 发送axios-get请求
                let { data } = await axios({
                    method: 'get',
                    // 利用数组下标进行tab切换
                    url: 'http://192.168.218.1:5522/tabs?id=' + (index + 1),
                });
                let { content } = data;

                [...mainEle][index].innerText = content;
            });
        });

        //默认让第一个选项卡自执行一次
        lisELe[0].click();

    </script>

</body>

</html>